package com.han.controller;

import com.han.dao.GoodsDao;
import com.han.model.GoodsEntity;
import com.han.model.ResultInfo;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created on 2019/3/28.
 * @author han
 * 商品查询
 */

@RestController
@RequestMapping("/wujin")
public class GoodsController {

    //注入dao
    @Resource
    public GoodsDao goodsDao;


    @RequestMapping("/formpage")
    public ModelAndView createNew(Model model){
        model.addAttribute("title", "新增商品信息");
        return new ModelAndView("form","goodsModel",model);
    }


    @RequestMapping("/getGoods")
    @ResponseBody
    public List<Map> getAll(){

        List<Map> allGoods = goodsDao.getAllGood();
        return allGoods;
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Integer goods_id, Model model) {
        Map goodMap = goodsDao.getGoodById(goods_id);
        model.addAttribute("goods",goodMap);
        model.addAttribute("title", "查看商品信息");
        return new ModelAndView("view","goodsModel",model);
    }

    @GetMapping("/list")
    public ModelAndView list(Model model) {
        List<Map> allGoods = goodsDao.getAllGood();
        model.addAttribute("goodsList",allGoods);
        model.addAttribute("title", "商品管理");
        return new ModelAndView("list","goodsModel",model);
    }

    @GetMapping("/delete/{id}")
    public ModelAndView deleteUser(@PathVariable("id") Integer goods_id) {
        goodsDao.deleteGoodById(goods_id);
        return new ModelAndView("redirect:/wujin/list");
    }


    @RequestMapping("/form")
    public ModelAndView  createForm(GoodsEntity goodsEntity) {

        ResultInfo resultInfo = new ResultInfo();
        Integer result = goodsDao.insertGoods(goodsEntity);
        if (result!=0){
            resultInfo.setMassage("成功");
            resultInfo.setSuccess(true);
        }else{
            resultInfo.setMassage("失败");
            resultInfo.setSuccess(false);
        }
        return new ModelAndView("redirect:/wujin/list");//重定向到list页面;

    }
}
